package com.wx.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.eova.common.Easy;
import com.eova.common.utils.xx;
import com.eova.core.IndexController;
import com.eova.interceptor.AuthInterceptor;
import com.eova.interceptor.LoginInterceptor;
import com.jfinal.aop.Clear;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.wx.model.PartyGetBonusRecord;
import com.wx.model.PartyInfo;
import com.wx.model.PartyLotteryNum;
import com.wx.model.PartyPrizeDetail;
import com.wx.model.PartyRule;
import com.wx.model.PartyUser;
import com.wx.model.PartyUserLotteryNum;
import com.wx.service.MarketingService;
import com.wx.service.UserIndexService;
import com.wx.sql.MarketingSql;
import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.http.HttpUtil;
import com.xiaoleilu.hutool.json.JSONArray;
import com.xiaoleilu.hutool.json.JSONUtil;
import com.xiaoleilu.hutool.util.StrUtil;

@Clear({LoginInterceptor.class,AuthInterceptor.class})
public class K2ApiController extends IndexController{
	
	
//	"JSONDATA"={
//		    "user_ids":["2003","2004","2005","2006"],
//		    "area_id":"300100",
//		    "party_id":"27",
//		}
	
	public void getUserDrawByList(){
		String req = getPara("JSONDATA");
		String errMessage = "";
		List<Map> retList = new ArrayList<Map>();
		try{
			if(!StrUtil.isBlank(req)){
				System.out.println(req);
				Map map = JSONUtil.parseObj(req);
				//获得活动ID
				Integer partyid = (int)map.get("party_id");
				if(partyid!=null){
					PartyInfo party = PartyInfo.dao.findById(partyid);
					if(party!=null){
						//判断当前是否在正常时间以内
						if(DateUtil.isIn(new Date(), party.getStartTime(), party.getEndTime())){
							//根据用户ID获取抽奖次数 
							JSONArray userIds =  (JSONArray) map.get("user_ids");
							//循环解析每个用户的抽奖次数
							if(userIds!=null &&userIds.size()>0){
								for(int i=0;i<userIds.size();i++){
									String str = (String) userIds.get(i);
									Map newMap = new HashMap<>();
									newMap.put("USER_ID", str);
									//获取用户
									List<PartyUser> userList = PartyUser.dao.find("select * from party_user d where d.user_code =?",str);
									if(userList.size()>0){
										
										List<PartyLotteryNum> pList = PartyLotteryNum.dao.find("select * from party_user_lottery_num d where d.user_id=? and d.party_id = ?",userList.get(0).getId(),partyid);
										if(pList.size()>0){
											newMap.put("DRAW_NUM", pList.get(0).getLotteryNum());
										}else{
											newMap.put("DRAW_NUM", 0);
										}
									}else{
										newMap.put("DRAW_NUM", 0);
									}
									
									retList.add(newMap);
								}
							}else{
								errMessage = "用户ID为空";
							}
							
						}else{
							errMessage = "活动未开启或已结束";
						}
					}else{
						errMessage = "未查询到此活动";
					}
				}else{
					errMessage = "未提供活动ID";
				}
			}else{
				errMessage = "接口传参数据为空";
			}
		}catch(Exception e){
			e.printStackTrace();
			errMessage= "系统异常";
		}
		if(retList.size()>0){
			renderJson(Ret.ok("RETLIST", retList));
		}else{
			System.out.println("======="+Ret.fail("ERR",errMessage));
			renderJson(Ret.fail("ERR",errMessage));
		}
	}
//	 "JSONDATA"={
//			    "user_id":"2003",
//			    "area_id":"300100",
//			    "party_id":"27",
//			    "order_data":[
//			        {
//			            "order_no":"20180927162301522",
//			            "money":"489.56"
//			        }
//
//			        {
//			            "order_no":"20180927162302587",
//			            "money":"895.56"
//			        }
//			    ]
//			}
	public void setUserDrawNum(){
		String req = getPara("JSONDATA");
		String errMessage = "";
		Map retMap = new HashMap<>();
		try{

			if(!StrUtil.isBlank(req)){
				System.out.println(req);
				Map map = JSONUtil.parseObj(req);
				//获得活动ID
				Integer partyid = (int)map.get("party_id");
				if(partyid!=null){
					PartyInfo party = PartyInfo.dao.findById(partyid);
					if(party!=null){
						//判断当前是否在正常时间以内
						if(DateUtil.isIn(new Date(), party.getStartTime(), party.getEndTime())){
							if(party.getReduceType()==0){
								//解析获得订单集合
								JSONArray orderDatas =  (JSONArray) map.get("order_data");
								if(orderDatas!=null&&orderDatas.size()>0){
									//下单次数
									int xdcs =  0;
									int cs = 0;
									for(int i=0;i<orderDatas.size();i++){
										Map orderMap = (Map) orderDatas.get(i);
										if(Double.valueOf((String)orderMap.get("money"))>party.getReduceNum()){
											xdcs = xdcs +1;
										}else{
											
										}
									}
									if(xdcs >0){
										List<PartyUser> userList = PartyUser.dao.find("select * from party_user d where d.user_code =?",map.get("user_id"));
										PartyUser user = null;
										if(userList.size()>0){
											user = userList.get(0);
										}else{
											user = new PartyUser();
											user.setUserName((String)map.get("user_id"));
											user.setPhone("");
											user.setUserCode((String)map.get("user_id"));
											user.setCreateDate(new Date());
											user.setUserSource((String)map.get("area_id"));
											user.setUserType(1);
//											user.setRequestKey(key);
											user.save();
										}
										//获取用户在此活动已抽奖次数
										Record r = Db.findFirst("select ifnull(sum(prize_num),1) maxcs from party_get_bonus_record d where d.user_id = ? and d.party_id =?",user.getId(),partyid);
										int maxcs = 0;
										int dtcs = 0;
										if(r !=null){
											if(r.getInt("maxcs")==0){
												maxcs = 1;
											}else{
												maxcs = r.getInt("maxcs");
											} 
										}
										//获取奖励规则
										List<PartyRule> partyRuleList = PartyRule.dao.find("select * from party_rule d where d.party_id = ?",partyid);
										PartyRule pr = partyRuleList.get(0);
										//获取用户当天在此活动已抽奖次数
										r = Db.findFirst("select  ifnull(sum(prize_num),0) num from party_get_bonus_record d where d.user_id=? and to_days(d.create_time) = to_days(now()) ",user.getId());
										if(r !=null){
											dtcs = r.getInt("num");
										}
										if(pr.getLimitOrderNum()<=dtcs||maxcs>=party.getMaxnum()){
											errMessage = "用户获得抽奖次数已达到上限"; 
										}else{
											//计算抽奖次数
											cs = pr.getOrderNum()*xdcs;
											if(cs>0){
//												if(cs>maxcs){
//													//大于最大抽奖次数时
//													cs = maxcs;
//												}
												if(cs+dtcs>=pr.getLimitOrderNum()){
													cs = pr.getLimitOrderNum() - dtcs;
												}
												//更新用户剩余次数表
												List<PartyLotteryNum> partyLotteryNumList = PartyLotteryNum.dao.find("select * from party_user_lottery_num d where d.user_id =? and d.party_id = ?",user.getId(),partyid);
												PartyLotteryNum p = null;
												if(partyLotteryNumList.size()>0){
													p = partyLotteryNumList.get(0);
													p.setLotteryNum(p.getLotteryNum()+cs);
													p.setUpdateDate(new Date());
													p.update();
												}else{
													p = new PartyLotteryNum();
													p.setLotteryNum(cs);
													p.setCreateDate(new Date());
													p.setPartyId(partyid);
													p.setUserId(user.getId());
													p.save();
												}
												//新增用户抽奖记录表
												PartyGetBonusRecord pubs  = new PartyGetBonusRecord();
												pubs.setCreateTime(new Date());
												pubs.setPartyId(partyid);
												pubs.setPrizeNum(cs);
												pubs.setUserId(user.getId());
												pubs.save();
											
											}
										}
									}else{
										
									}
									retMap.put("CS", cs);
									retMap.put("USER_ID", map.get("user_id"));
									
								}else{
									errMessage = "无订单集合";
								}
							}else{
								errMessage = "积分活动无法获得抽奖次数";
							}
						}else{
							errMessage = "活动未开启或已结束";
						}
					}else{
						errMessage = "未查询到此活动";
					}
				}else{
					errMessage = "用户ID为空";
				}
			}else{
				errMessage = "接口传参数据为空";
			}
		}catch(Exception e){
			e.printStackTrace();
			errMessage = "系统异常";
		}
		if(errMessage.length()==0){
			renderJson(Ret.ok("RET", retMap));
		}else{
			System.out.println("======="+Ret.fail("ERR",errMessage));
			renderJson(Ret.fail("ERR",errMessage));
		}
	}
	
}
